import { validatenull } from './validate'
import sha256 from 'crypto-js/sha256';
import Base64 from 'crypto-js/enc-base64';
import axios from 'axios';
//表单序列化
export const serialize = data => {
  let list = [];
  Object.keys(data).forEach(ele => {
    list.push(`${ele}=${data[ele]}`)
  })
  return list.join('&');
};
export const getObjType = obj => {
  var toString = Object.prototype.toString;
  var map = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object'
  };
  if (obj instanceof Element) {
    return 'element';
  }
  return map[toString.call(obj)];
};
/**
 * 对象深拷贝
 */
export const deepClone = data => {
  var type = getObjType(data);
  var obj;
  if (type === 'array') {
    obj = [];
  } else if (type === 'object') {
    obj = {};
  } else {
    //不再具有下一层次
    return data;
  }
  if (type === 'array') {
    for (var i = 0, len = data.length; i < len; i++) {
      obj.push(deepClone(data[i]));
    }
  } else if (type === 'object') {
    for (var key in data) {
      obj[key] = deepClone(data[key]);
    }
  }
  return obj;
};
/**
 * 设置灰度模式
 */
export const toggleGrayMode = (status) => {
  if (status) {
    document.body.className = document.body.className + ' grayMode';
  } else {
    document.body.className = document.body.className.replace(' grayMode', '');
  }
};
/**
 * 设置主题
 */
export const setTheme = (name) => {
  document.body.className = name;
}

/**
 * 加密处理
 */
export const encryption = (params) => {
  let {
    data = {},
    type,
    param,
    key
  } = params;
  let result = JSON.parse(JSON.stringify(data));
  if (type == 'Base64') {
    param.forEach(ele => {
      result[ele] = Base64.stringify(result[ele]);
    })
  } else if (type == 'Aes') {
    param.forEach(ele => {
      result[ele] = sha256(result[ele], key)
    })

  }
  return result;
};


/**
 * 浏览器判断是否全屏
 */
export const fullscreenToggel = () => {
  if (fullscreenEnable()) {
    exitFullScreen();
  } else {
    reqFullScreen();
  }
};
/**
 * esc监听全屏
 */
export const listenfullscreen = (callback) => {
  function listen () {
    callback()
  }
  document.addEventListener("fullscreenchange", function () {
    listen();
  });
  document.addEventListener("mozfullscreenchange", function () {
    listen();
  });
  document.addEventListener("webkitfullscreenchange", function () {
    listen();
  });
  document.addEventListener("msfullscreenchange", function () {
    listen();
  });
};
/**
 * 浏览器判断是否全屏
 */
export const fullscreenEnable = () => {
  var isFullscreen = document.isFullScreen || document.mozIsFullScreen || document.webkitIsFullScreen
  return isFullscreen;
}

/**
 * 浏览器全屏
 */
export const reqFullScreen = () => {
  if (document.documentElement.requestFullScreen) {
    document.documentElement.requestFullScreen();
  } else if (document.documentElement.webkitRequestFullScreen) {
    document.documentElement.webkitRequestFullScreen();
  } else if (document.documentElement.mozRequestFullScreen) {
    document.documentElement.mozRequestFullScreen();
  }
};
/**
 * 浏览器退出全屏
 */
export const exitFullScreen = () => {
  if (document.documentElement.requestFullScreen) {
    document.exitFullScreen();
  } else if (document.documentElement.webkitRequestFullScreen) {
    document.webkitCancelFullScreen();
  } else if (document.documentElement.mozRequestFullScreen) {
    document.mozCancelFullScreen();
  }
};
/**
 * 递归寻找子类的父类
 */

export const findParent = (menu, id) => {
  for (let i = 0; i < menu.length; i++) {
    if (menu[i].children.length != 0) {
      for (let j = 0; j < menu[i].children.length; j++) {
        if (menu[i].children[j].id == id) {
          return menu[i];
        } else {
          if (menu[i].children[j].children.length != 0) {
            return findParent(menu[i].children[j].children, id);
          }
        }
      }
    }
  }
};
/**
 * 判断2个对象属性和值是否相等
 */

/**
 * 动态插入css
 */

export const loadStyle = url => {
  const link = document.createElement('link');
  link.type = 'text/css';
  link.rel = 'stylesheet';
  link.href = url;
  const head = document.getElementsByTagName('head')[0];
  head.appendChild(link);
};
/**
 * 判断路由是否相等
 */
export const diff = (obj1, obj2) => {
  delete obj1.close;
  var o1 = obj1 instanceof Object;
  var o2 = obj2 instanceof Object;
  if (!o1 || !o2) { /*  判断不是对象  */
    return obj1 === obj2;
  }

  if (Object.keys(obj1).length !== Object.keys(obj2).length) {
    return false;
    //Object.keys() 返回一个由对象的自身可枚举属性(key值)组成的数组,例如：数组返回下表：let arr = ["a", "b", "c"];console.log(Object.keys(arr))->0,1,2;
  }

  for (var attr in obj1) {
    var t1 = obj1[attr] instanceof Object;
    var t2 = obj2[attr] instanceof Object;
    if (t1 && t2) {
      return diff(obj1[attr], obj2[attr]);
    } else if (obj1[attr] !== obj2[attr]) {
      return false;
    }
  }
  return true;
}
/**
 * 根据字典的value显示label
 */
export const findByvalue = (dic, value) => {
  let result = '';
  if (validatenull(dic)) return value;
  if (typeof (value) == 'string' || typeof (value) == 'number' || typeof (value) == 'boolean') {
    let index = 0;
    index = findArray(dic, value);
    if (index != -1) {
      result = dic[index].label;
    } else {
      result = value;
    }
  } else if (value instanceof Array) {
    result = [];
    let index = 0;
    value.forEach(ele => {
      index = findArray(dic, ele);
      if (index != -1) {
        result.push(dic[index].label);
      } else {
        result.push(value);
      }
    });
    result = result.toString();
  }
  return result;
};
/**
 * 根据字典的value查找对应的index
 */
export const findArray = (dic, value) => {
  for (let i = 0; i < dic.length; i++) {
    if (dic[i].value == value) {
      return i;
    }
  }
  return -1;
};
/**
 * 生成随机len位数字
 */
export const randomLenNum = (len, date) => {
  let random = '';
  random = Math.ceil(Math.random() * 100000000000000).toString().substr(0, len ? len : 4);
  if (date) random = random + Date.now();
  return random;
};
/**
 * 打开小窗口
 */
export const openWindow = (url, title, w, h) => {
  // Fixes dual-screen position                            Most browsers       Firefox
  const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left
  const dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top

  const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width
  const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height

  const left = ((width / 2) - (w / 2)) + dualScreenLeft
  const top = ((height / 2) - (h / 2)) + dualScreenTop
  const newWindow = window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left)

  // Puts focus on the newWindow
  if (window.focus) {
    newWindow.focus()
  }
}


export const getScreen = (isCollapse) => {
  if (document.body.clientWidth <= 768) {
    return !isCollapse
  } else {
    return isCollapse
  }
}

/**
 * 取出字符串中小括号内的内容
 * @param text
 * @returns {string}
 */
export const getParenthesesStr = (text) => {
  let result = ''
  if (validatenull(text))
    return result
  let regex = /\((.+?)\)/g;
  let options = text.match(regex)
  if (!validatenull(options)) {
    let option = options[0]
    if (!validatenull(option)) {
      result = option.substring(1, option.length - 1)
    }
  }
  return result
}

/**
 * 标准时间转年月日
 * @param date
 * @returns {string}
 */
export const transformTime = (date) => {
  let d = new Date(date);
  let datetime =  d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
  return datetime;
}

/**
 * 标准时间转换为 YYYY-mm-dd HH:MM:SS
 * @param fmt YYYY-mm-dd HH:MM:SS
 * @param date 时间
 * @returns {*}
 */
export const dateFormat = (fmt, date) =>{
  let ret
  const opt = {
    'Y+': date.getFullYear().toString(), // 年
    'm+': (date.getMonth() + 1).toString(), // 月
    'd+': date.getDate().toString(), // 日
    'H+': date.getHours().toString(), // 时
    'M+': date.getMinutes().toString(), // 分
    'S+': date.getSeconds().toString(), // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  }
  for (let k in opt) {
    ret = new RegExp('(' + k + ')').exec(fmt)
    if (ret) {
      fmt = fmt.replace(ret[1], ret[1].length === 1 ? opt[k] : opt[k].padStart(ret[1].length, '0'))
    }
  }
  return fmt
}

/**
 * 获取距离某一日期还有几天
 * @param targetDate
 * @returns {number}
 */
export const getDiffDate = (targetDate)=> {
  let date1 = new Date(targetDate);
  let date2 = new Date();
  date1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate());
  date2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate());
  const diff = date1.getTime() - date2.getTime();
  const diffDate = diff / (24 * 60 * 60 * 1000);
  return diffDate;
}

/**
 * 判断两个时间的大小
 * @param date1
 * @param date2
 * @returns {boolean}
 */
export const compareDate = (date1,date2)=>{
  let oDate1 = new Date(date1);
  let oDate2 = new Date(date2);
  if(oDate1.getTime() > oDate2.getTime()){
    return true; //第一个大
  } else {
    return false; //第二个大
  }
}

/**
 * 获取指定日期前或者后指定间隔时间代码
 * @param sdate 当前日期
 * @param interval 日期前后 0当天 -1前一天 1后一天
 * @param caret -
 * @returns {*}
 */
export const getNowFormatDate = (sdate,interval,caret) =>{
  let patt1 =  /^\d{4}-([0-1]?[0-9])-([0-3]?[0-9])$/;  //判断输入的日期是否符合格式正则表达式
  if(!(sdate && typeof(sdate) == "string" &&  patt1.test(sdate))){
    sdate = new Date(); //不满足日期的则使用当前年月日
  }
  interval = isNaN(parseInt(interval)) ? 0 : parseInt(interval);//若没有输入间隔，则使用当前日
  caret = (caret && typeof(caret) == "string") ? caret : "";
  let gdate = new Date(sdate).getTime();//获取指定年月日
  gdate = gdate + 1000*60*60*24*interval; //加减相差毫秒数
  let speDate = new Date(gdate);//获取指定好毫秒数时间
  let preYear = speDate.getFullYear();
  let preMonth = speDate.getMonth() + 1;
  let preDay = speDate.getDate();
  preMonth = (preMonth < 10) ? ("0" + preMonth) :preMonth;
  preDay = (preDay < 10) ? ("0" + preDay) :preDay;
  let preDate =  preYear + caret +  preMonth + caret + preDay;
  return preDate;
}

/**
 * 单张图片下载
 * @param imgSrc 图像链接
 * @param name 图片名称
 */
export const downloadPicture =(imgSrc, name)=>
{
  axios.get('/..'+imgSrc,{
    responseType:'arraybuffer'
  }).then(res=>{
    const url = URL.createObjectURL(new Blob([res.data],{type:res.headers['content-type']}));
    const a = document.createElement("a");
    a.download = name || "photo";
    a.href = url;
    a.click();
    a.remove();
    URL.revokeObjectURL(url);
  })
}


/**
 * 内存转换
 * @param num
 * @returns {string}
 */
export const diskSize =(num) => {
  if (num === 0) return '0 B';
  var k = 1024; //设定基础容量大小
  var sizeStr = ['B','KB','MB','GB','TB','PB','EB','ZB','YB']; //容量单位
  var i = 0; //单位下标和次幂
  for(var l=0;l<8;l++){   //因为只有8个单位所以循环八次
    if(num / Math.pow(k, l) < 1){ //判断传入数值 除以 基础大小的次幂 是否小于1，这里小于1 就代表已经当前下标的单位已经不合适了所以跳出循环
      break; //小于1跳出循环
    }
    i = l; //不小于1的话这个单位就合适或者还要大于这个单位 接着循环
  }

  return (num / Math.pow(k, i)).toFixed(0) + ' ' + sizeStr[i];  //循环结束 或 条件成立 返回字符

}
